;-----------------------------------------
; 	PicOS Project
;
; 	HEPIA 2014 - Florent Gluck
;
;	Denis Voirol		Pierre Kiss
;	Ruben Magnin		Alina Stanculescu
;	Sebastien Beureux	Julien Cornut
;-----------------------------------------
;
;	bootsect_asm.s
;
;	Bootloader
;
;-----------------------------------------

KERN_SEG        equ     0x1000  ; kernel loaded at this address
KERN_SIZE       equ     16      ; max kernel size in sectors (8KB)
KERN_START      equ     1       ; sector where kernel resides (0-indexed)
BOOT_DRIVE      equ     0x80    ; boot drive (0x00 = floppy, 0x80 = HDD)
STACK_OFFS      equ     0xfbfe  ; offset at which the stack starts
BOOT_SEG	equ	0x7c0

[BITS 16]
[ORG 0x0]

	; IMPORTANT: BIOS loads the 1st sector at address 0x7c0:0

	; initialize segments 
	mov ax, KERN_SEG   ; all segments point to the same address (tiny memory model!)
	mov ds, ax
	mov es, ax
	mov ss, ax

	; stack starts at KERN_SEG:STACK_OFFS (grows downward)
	mov ax, STACK_OFFS
	mov sp, ax
	mov bp, ax

	; reset drive
	xor ax, ax
	mov dl, BOOT_DRIVE
	int 0x13

	; display message with interruption
	push es
	mov ah, 0xE 		; interruption func
	mov bx, 0x00
	mov cx, BOOT_SEG	; boot segment
	mov es, cx
	mov di, msg			; msg pointer
	msg_disp:
		mov al, byte [es:di]
		int 0x10		; interruption 10h
		add di,1
		cmp al,0
		jne msg_disp	; loop while al /= 0
	pop es				; restaure es

	; load kernel at address KERN_SEG:0
	; uses BIOS extended read (function 0x42 of int 0x13)
	push ds
	mov ah, 0x42		; interruption func
	mov si, packet
	mov cx, BOOT_SEG	; boot segment
	mov ds, cx
	int 0x13			; interruption 13h
						; param : dl , [ds:si]
	pop ds				; restaure ds

	; jump to kernel
	jmp KERN_SEG:0

; memory structure required by the extended read call
packet:
	size           db 0x10
	reserved       db 0
	sect_count     dw KERN_SIZE
	addr_offset    dw 0
	addr_segment   dw KERN_SEG
	first_sect     dq KERN_START ; first sector to read (0-indexed)

	msg db "Loading kernel...",13,10,0

	; fill with nop instructions until offset 510
	times 510-($-$$) db 0x90

	; last 2 bytes of sector: indicate a bootable sector
	dw 0xAA55
